import React, { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {getStockDiffQuantity, getStockInGoodsQuantity} from "@/services/echart/api";
import {Bar, Base, Pie} from "@ant-design/charts";
import {Card,Row,Col} from "antd";

const StockInGoodsChart: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [data, setData] = useState<API.GoodsQuantity[]>([]);

  const columns: ProColumns<API.StockDiffQuantity>[] = [
    {
      title: '货品编码',
      width: 120,
      dataIndex: 'goodsCode',
      hideInSearch: true,
      editable: false,
    },
    {
      title: '货品名称',
      width: 120,
      dataIndex: 'goodsName',
      editable: false,
      hideInSearch: true,
    },
    {
      title: '入库数量',
      hideInSearch: true,
      width: 120,
      editable: false,
      dataIndex: 'quantity',
    },
  ];

  const loadData = async () => {
    const res = await getStockInGoodsQuantity();
    if (res.code != 0) {
      console.error('库存数据加载失败', res.message);
      return;
    }
    setData(res?.data || []);
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <>
      <Row justify="start">

        <Col span={12}>
          <Card title='货品入库柱状图'>
            <Base {...{
              type: 'spaceLayer',
              data: data,
              children: [
                {
                  type: 'interval',
                  encode: { x: 'goodsName', y: 'quantity', color: 'goodsCode' },
                  transform: [{ type: 'sortX', reverse: true, by: 'y' }],
                  scale: { color: { palette: 'cool', offset: (t) => t * 0.8 + 0.1 } },
                }
              ],
            }}/>
          </Card>

        </Col>
        <Col span={12}>
          <Card title='货品入库扇形图'>
            <Pie {...{
              data: data,
              angleField: 'quantity',
              colorField: 'goodsCode',
              label: {
                text: 'goodsName',
                style: {
                  fontWeight: 'bold',
                },
              },
              legend: {
                color: {
                  title: false,
                  position: 'right',
                  rowPadding: 5,
                },
              },
            }}/>
          </Card>
        </Col>
      </Row>

      <ProTable<API.GoodsQuantity>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={data}
        request={async () => {
          await loadData();
          return data;
        }}
        searchFormRender={() => <></>}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        headerTitle="商品入库数量"
      />
    </>
  );
};

export default StockInGoodsChart;
